﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LGE;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Xna.Framework.GamerServices;

namespace EggCatcher
{
    class ScoreScreen : GameScreen
    {
        int score;
        readonly String highScoresFileName = "HighScores";
        HighScoreData highScoreData;
        Texture2D backGround;
        bool scoreSaved = false;
        int scoreIndex = -1;
        string song = "Sounds\\Score";

        public ScoreScreen(int score)
            : base()
        {
            this.score = score;
        }

        public override void LoadContent()
        {
            Engine.AddSong(song);
            Engine.PlaySong(song);
            backGround = Engine.Load<Texture2D>("Images\\bg_scorescreen");

            // Load the data to save
            highScoreData = LoadHighScores(highScoresFileName);


            // Check if actual score is better than any of the rank and get its position
            for (int i = 0; i < highScoreData.Count; i++)
            {
                if (score > highScoreData.Score[i])
                {
                    scoreIndex = i;
                    break;
                }
            }
            if (scoreIndex > -1) SaveScore("Player");
            /*
            if (scoreIndex > -1)
                Input.CallVK("Nome", "Parabéns! Você atingiu uma das dez melhores pontuações do ranking! Insira seu nome:");
            else
                scoreSaved = true;*/
        }

        public override void Update(GameTime gameTime)
        {
            /*if (!scoreSaved)
            {
                String temp = Input.GetVKResult;
                if (temp != null && temp != "WAITING")
                {
                    if (temp != "CANCEL" && temp != "")
                        SaveScore(temp);
                    scoreSaved = true;
                }
                return;
            }*/

            if (Input.KeyPressed(Keys.Enter)) GameScreenManager.ChangeScreen(new StartScreen());
        }

        public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(backGround, Vector2.Zero, Color.White);
            spriteBatch.DrawString(EggCatcher.Font, "FINAL SCORE:  " + score, new Vector2(Engine.viewport.Width / 2, 245), Color.Black, 0, EggCatcher.Font.MeasureString("FINAL SCORE: " + score) / 2, 1, SpriteEffects.None, 0);
            for (int i = 0; i < highScoreData.Count; ++i)
            {
                spriteBatch.DrawString(EggCatcher.Font, highScoreData.PlayerName[i], new Vector2(520, 290 + i * 25), Color.Black);
                spriteBatch.DrawString(EggCatcher.Font, highScoreData.Score[i].ToString(), new Vector2(770, 290 + i * 25), Color.Black);
            }
        }

        public void SaveScore(String name)
        {
            if (name.Length > 8) name = name.Remove(8);

            // Do swaps
            for (int i = highScoreData.Count - 1; i > scoreIndex; i--)
            {
                highScoreData.PlayerName[i] = highScoreData.PlayerName[i - 1];
                highScoreData.Score[i] = highScoreData.Score[i - 1];
            }
            highScoreData.PlayerName[scoreIndex] = name;
            highScoreData.Score[scoreIndex] = score;

            // Open the file, creating it if necessary
            FileStream stream = File.Open(highScoresFileName, FileMode.Create);
            try
            {
                // Convert the object to XML data and put it in the stream
                XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                serializer.Serialize(stream, highScoreData);
            }
            finally { stream.Close(); }
        }

        public HighScoreData LoadHighScores(String fileName)
        {
            HighScoreData data = new HighScoreData();

            // Open the file
            FileStream stream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Read);
            try
            {
                // Read the data from the file
                XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                data = (HighScoreData)serializer.Deserialize(stream);
            }
            catch { }
            finally { stream.Close(); }
            return data;
        }
    }

    public class HighScoreData
    {
        public string[] PlayerName;
        public int[] Score;

        public int Count;

        public HighScoreData()
        {
            Count = 10;
            PlayerName = new string[Count];
            Score = new int[Count];
            for (int i = 0; i < 10; ++i)
            {
                PlayerName[i] = "Player";
                Score[i] = 0;
            }

        }
    }
}